import 'dart:async';

// import 'package:alarm/alarm.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:intl/intl.dart';
import 'package:valovault_reminder/common/config/val_client_url_path.dart';
import 'package:valovault_reminder/http/val_dio_fetch_kit.dart';
import 'package:valovault_reminder/pages/base/val_common_navigationbar_page.dart';
import 'package:valovault_reminder/pages/home/val_application_home_page.dart';
import 'package:valovault_reminder/pages/home/models/val_post_record_model.dart';
import 'package:valovault_reminder/pages/message/val_audio_player.dart';
import 'package:valovault_reminder/pages/mine/val_my_home_page.dart';
import 'package:valovault_reminder/pages/notice/val_notice_list_page.dart';
import 'package:valovault_reminder/pages/publish/val_publish_car_content_page.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:valovault_reminder/util/val_eventbus_manager.dart';
import 'common/bean/val_user_base_info_model.dart';
import 'common/ui/val_ui_kit_dialog_impl.dart';
import 'common/util/val_app_state_tool.dart';
import 'common/util/val_apple_pay_tool.dart';
import 'pages/notice/val_notice_work_page.dart';

class ValApplicationBaseRootPage extends StatefulWidget {
  const ValApplicationBaseRootPage({super.key});

  @override
  State<ValApplicationBaseRootPage> createState() => _ValApplicationBaseRootPageState();
}

class _ValApplicationBaseRootPageState extends ValCommonNavigationPageState<ValApplicationBaseRootPage> {
  Timer? _timer;
  var alarmCache = <String, dynamic>{};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ///切换tab
    onTapTabBar = (int index) {
      // tabBarColor = Colors.black;//(index == 1) ? Colors.black : Colors.white;
    };
    requestBaseConfigValue();
    Future.delayed(const Duration(milliseconds: 100)).then((value) => loadDeviceInfo());
    ValAudioPlayer().init();
    ValApplePayTool().init();
    // requestTrackingAuthorization();
    // 闹钟
    configAlarm();
    ValEventbusManager.getInstance().eventBus.on().listen((event) {
      if (event.toString() != "alarmDataUpdate") {
        return;
      }
      alarmCache.clear();
      _startTimer();
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startTimer() async {
    _timer?.cancel();
    List<ValPostRecordModel> list = await ValPostRecordModel().readCategoryDb('3');
    if (list.isEmpty) {
      return;
    }
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      fireAlarmData(list);
    });
  }

  Future<void> configAlarm() async {
    // final alarmSetting = AlarmSettings(id: 11, dateTime: DateTime.now(), assetAudioPath: 'assets/space_voice.m4a');
    // await Alarm.set(alarmSettings: alarmSetting);
    if (ValAppStateTool().isAlarmFinished) {
      return;
    }
    ValAppStateTool().isAlarmFinished = true;
    requestUserAccountData(0);
    // Alarm.init();
    // Alarm.ringStream.stream.listen((event) {
    //   Alarm.stop(event.id);
    //   requestUserAccountData(event.id);
    // });
  }

  ///获取账号信息
  void requestUserAccountData(int eventId) {
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.userInfo, {'userId' : ValAppStateTool().userId},
            (data, errorCode, message){
          if (errorCode == 0) {
            ValUserBaseInfoModel user = ValUserBaseInfoModel.fromJson(data);
            ValAppStateTool().accountInfo = user;
            _startTimer();
          }
        }, (err) {

        });
  }

  Future<void> fireAlarmData(List<ValPostRecordModel> list) async {
    if (list.isEmpty) {
      return;
    }

    int timestamp = DateTime.now().millisecondsSinceEpoch;
    String customFormat = 'yyyy.MM.dd HH:mm';
    DateFormat formatter = DateFormat(customFormat);
    for (ValPostRecordModel data in list) {
      String timeValue = '${data.publishDate} ${data.image}';
      DateTime noticeDate = formatter.parse(timeValue);
      int noticeTimestamp = noticeDate.millisecondsSinceEpoch;
      String dataId = data.id.toString();
      if (alarmCache.keys.isNotEmpty && alarmCache.keys.contains(dataId) && alarmCache[dataId] == '1') {
        continue;
      }
      if (!data.collected &&  noticeTimestamp <= timestamp) {
        alarmCache[dataId] = '1';
        ValUIKitDialogImpl.showCenter(ValNoticeWorkPage(postModel: data,));
        break;
      }
    }
  }

  void requestTrackingAuthorization() async {
    final status = await AppTrackingTransparency.requestTrackingAuthorization();
  }


  void loadDeviceInfo() async {
    String? identifier;
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Theme.of(context).platform == TargetPlatform.iOS) {
      IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
      identifier = iosDeviceInfo.identifierForVendor; // unique ID on iOS
    }
  }

  void requestBaseConfigValue() {
    /// 获取配置项
    ValAppStateTool.getConfigFromNet(() async {

    });
  }

  @override
  List<BottomNavigationBarItem> getBottomNavigationBarItems(BuildContext context) {
    return [
      barItemWithImage(imageName: 'val_root_bar_home.png', selectedImageName: 'val_root_bar_home_s.png'),
      barItemWithImage(imageName: 'val_root_bar_add.png', selectedImageName: 'val_root_bar_add_s.png'),
      barItemWithImage(imageName: 'val_root_bar_notice.png', selectedImageName: 'val_root_bar_notice_s.png'),
      barItemWithImage(imageName: 'val_root_bar_mine.png', selectedImageName: 'val_root_bar_mine_s.png'),
    ];
  }

  @override
  List<Widget> getWidgets() {
    return [const ValApplicationHomePage(), const ValPublishCarContentPage(), const ValNoticeListPage(), const ValMyHomePage()];
  }

}
